<template>
    <div class="item-title" :class="[customClass]">
        <span class="title">{{ hedaerTitle || $t('message.text.memberPermission') }}</span>
        <span class="add-auth" @click="addRole" v-if="!disabled"><i
                class="knowledge-iconfont keowledge-tianjia"></i>{{ $t('message.buttons.addPermission') }}</span>
    </div>
    <div class="permission-content-item" v-for="(item, index) in permissionList" :key="index">
        <div class="add-or-del-box" v-if="!disabled">
            <div class="add" @click="handleUserSelectOpen(item, index)">
                <svg class="icon">
                    <use xlink:href="#keowledge-tianjia"></use>
                </svg>{{ $t('message.buttons.addMembers') }}
            </div>
            <div class="del" v-if="index > 0" @click="deleteGroupItem(item, index)">
                <svg class="icon">
                    <use xlink:href="#keowledge-shanchuquanxianzu"></use>
                </svg>{{ $t('message.buttons.deletePermission') }}
            </div>
        </div>
        <div class="persion-list-box">
            <div class="persion-item" v-for="(tag) in item.userInfoList" :key="tag.id">
                <img v-if="tag.headImg" :src="tag.headImg">
                <div v-tooltip-auto-show>
                    <el-tooltip :content="getTagName(tag)" effect="light">
                        <div class="name">{{ getTagName(tag) }}</div>
                    </el-tooltip>
                </div>
                <svg class="del-icon" v-if="!disabled" @click="handleDelUser(tag.id, item.userInfoList)">
                    <use xlink:href="#keowledge-danchuangguanbi"></use>
                </svg>
            </div>
        </div>
        <div class="checked-auth-list">
            <el-checkbox v-model="item.isAll" :indeterminate="getIndeterminate(index)"
                @change="(value) => { handleCheckAllChange(value, index) }"
                :disabled="disabled">{{ $t('message.buttons.checkAll') }}</el-checkbox>
            <div>
                <el-checkbox v-for="(itemA, indexA) in item.idcIdentifying" v-model="itemA.isSelect" :key="indexA"
                    :label="itemA.identifyingKey" style="width:120px;" :disabled="disabled"
                    @change="(value) => clickOne(value, indexA, index)">
                    {{ itemA.name }}
                </el-checkbox>
            </div>
        </div>
    </div>
    <userSelector ref="userSelectorRef" :selectable="true" :userEnable="true" :dept-enable="true" :roleEnable="true"
        :jobEnable="true" :groupEnable="true" @submit="addCheckUSer">
    </userSelector>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    getCurrentInstance
} from 'vue'

import { useRouter } from "vue-router"
import userSelector from "@/components/basic-assembly/userSelector.vue";
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits([""])
const props = defineProps({
    'custom-class': String,
    hedaerTitle: {
        type: String,
        default: ""
    },
    roleType: {
        type: Boolean,
        default: true
    },
    role: {
        type: Array,
        default() {
            return []
        }
    },
    infoData: {
        type: Object,
        default() {
            return {}
        }
    },
    roleList: {
        type: [Array],
        default: []
    },
    disabled: {
        type: Boolean,
        default: false
    }
})
interface permission {
    operation: Array<any>,
    personType: string,
    userInfoList: Array<any>,
    userIds: Array<any>,
    isAll: boolean,
    idcIdentifying: Array<any>
}
// watch(props.role,(newV)=>{
//     init()
// })
const permissionList = ref<permission[]>([])
const userSelectorRef = ref()
const currentIndex = ref(0)
const roleTypeTemp = ref(true)
function init() {
    permissionList.value = []
    roleTypeTemp.value = props.roleType
    if ((props.role && props.role.length > 0)) {
        permissionList.value = getRole(props.role)
    } else {
        permissionList.value = [{
            operation: [],
            personType: "custom",
            userInfoList: [],
            isAll: false,
            userIds: [],
            idcIdentifying: JSON.parse(JSON.stringify(props.roleList))
        }]
    }
}
// 获取权限列表
function getRole(arr) {
    const arrTemp = [...arr]
    arrTemp.forEach((item, key) => {
        if (!item.personType) {
            if (item.userInfoList && item.userInfoList.length > 0) {
                item.personType = 'custom'
            } else {
                item.personType = 'all'
            }
        }

        item.userInfoList.forEach(itemU => {
            itemU.id = itemU.userId
            itemU.type = itemU.dataAuthType
        })
        item.id = new Date().getTime() + key
        item.scopeList = item.scopeList ? item.scopeList : []
        item.isAll = false
        item.conditionList = item.conditionList ? item.conditionList : []
        item.operation = item.operation ? item.operation : []
        item.treeOperation = item.treeOperation ? item.treeOperation : []
        item.idcIdentifying = item.idcIdentifying ? item.idcIdentifying : []
        console.log(item.idcIdentifying)
        let count = 0
        item.idcIdentifying.forEach(item => {
            if (item.isSelect) {
                count++
            }
        })
        if (count >= item.idcIdentifying.length && count != 0) {
            item.isAll = true
        }
    })
    return arrTemp
}
function addRole() {
    const obj = {
        id: new Date().getTime(),
        operation: [],
        treeOperation: [],
        personType: 'custom',
        userInfoList: [],
        scopeList: [],
        conditionList: [],
        isAll: false,
        idcIdentifying: JSON.parse(JSON.stringify(props.roleList))
    }
    permissionList.value.push(obj)
}
// 删除单个权限组
function deleteGroupItem(obj, key) {
    permissionList.value.splice(key, 1)
}
function getTagName(obj) {
    let header = ''
    switch (obj.type) {
        case 'user':
            break;
        case 'role':
            header = $t('message.text.role');
            break;
        case 'dept':
            header = $t('message.text.depart');
            break;
        case 'group':
            header = $t('message.text.group');
            break;
        case 'job':
            header = $t('message.text.job');
            break;
        default: break;
    }
    return header + obj.name
}
function handleDelUser(id, arr) {
    const index = arr.findIndex(item => {
        return item.id === id
    })
    arr.splice(index, 1)
}
// 是否进行了全选
function handleCheckAllChange(value, index) {
    permissionList.value[index].idcIdentifying.forEach((item) => {
        item.isSelect = value
    })
}
function clickOne(value, indexA, index) {
    let isCheckNum = 0
    permissionList.value[index].idcIdentifying.forEach((item) => {
        if (item.isSelect) {
            isCheckNum++
        }
    })
    permissionList.value[index].isAll = isCheckNum >= permissionList.value[index].idcIdentifying.length
}
// 判定是否全选
function getIndeterminate(index) {
    let isCheckNum = 0
    permissionList.value[index].idcIdentifying.forEach((item) => {
        if (item.isSelect) {
            isCheckNum++
        }
    })
    // if(permissionList.value[index].isAll != isCheckNum>=permissionList.value[index].idcIdentifying.length){
    //     permissionList.value[index].isAll =  isCheckNum>=permissionList.value[index].idcIdentifying.length
    // }
    return isCheckNum != 0 && isCheckNum < permissionList.value[index].idcIdentifying.length
}
function addCheckUSer(checkList) {
    permissionList.value[currentIndex.value].userIds = checkList.map(item => {
        return item.id
    })
    permissionList.value[currentIndex.value].userInfoList = checkList
    // userSelectorRef.value.closeDialog()
}
function handleUserSelectOpen(item, index) {
    // userIds.value = item.userIds
    currentIndex.value = index
    userSelectorRef.value.openDialog(item.userInfoList)
}
// 获取当前设置的权限信息
function getPermissionData() {
    const arr: any[] = [...permissionList.value]
    const params = arr.map(item => {
        return {
            idcIdentifying: item.idcIdentifying,
            operation: item.personType == 'custom' ? item.operation : [],
            userInfoList: item.personType == 'custom' ? item.userInfoList : [],
            personType: item.personType || 'all',
            scopeList: item.personType == 'custom' ? item.scopeList : [],
            conditionList: item.personType == 'custom' ? item.conditionList : []
        }
    })
    return { role: params, roleType: roleTypeTemp.value }
}
defineExpose({
    init,
    getPermissionData
})
</script>
<style lang="scss" scoped>
.permission-content-item {
    padding: 16px 16px 16px 21px;
    background-color: #f5f6f7;
    border-radius: 6px;

    .add-or-del-box {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .add {
            width: 108px;
            height: 32px;
            background: #E4EDFF;
            border-radius: 4px;
            color: #1E6FFF;
            cursor: pointer;
            font-size: 14px;
            @include SourceHanSansCN-Regular;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .del {
            cursor: pointer;
            @include SourceHanSansCN-Regular;
            font-size: 14px;
            color: #FF194C;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .icon {
            width: 16px;
            height: 16px;
            margin-right: 4px;
        }
    }

    .persion-list-box {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-top: 16px;
        grid-column-gap: 16px;
        grid-row-gap: 16px;

        .persion-item {
            height: 48px;
            background: #FFFFFF;
            border-radius: 4px;
            display: flex;
            align-items: center;
            padding: 0px 8px;

            img {
                width: 32px;
                height: 32px;
                border-radius: 6px;
                overflow: hidden;
                margin-right: 8px;

            }

            .name {
                max-width: 140px;
                margin-right: 8px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                cursor: pointer;
            }

            .del-icon {
                fill: #6F7588;
                width: 14px;
                height: 14px;
                cursor: pointer;
            }
        }
    }
}

.permission-content-item+.permission-content-item {
    margin-top: 16px;
}
</style>